/*
 * @Author: CPS
 * @Date: 2020-08-07 16:22:19
 * @Last Modified by: CPS
 * @Last Modified time: 2020-08-13 00:07:56
 * @Projectname Electron-fileWatcher
 * @file_path D:\CPS\MyProject\Electron-fileWatcher\src\renderer\pages\fileWatcher\js\config\createSubPage.js
 * @Filename createSubPage.js
 */
'use strict'
let dataTemplate = {
  prefixName: '传入组件的前缀名',
  parent: '传入一个可挂载的html实例',
  tempalte: '一个生成html的函数',
  tempalteData: '传入一个模板需要的数据',
  icon: '传入icon元素',
}

// 定义组件前缀名
class createSubPage {
  constructor(data) {
    this.prefix = data['prefixName']
    this.template = data['template']
    this.parent = data['parent']
    this.data = {
      data: data['tempalteData'],
      icon: data['icon']
    }

    this.el = this.content = null
    this.init()
  }

  init(container, data) {
    // 创建元素实例
    this.el = document.createElement('section')
    this.el.className = this.el.id = this.prefix + 'container'
    this.parent.appendChild(this.el)
    this.el.innerHTML = this.template(this.data)

    // 延时弹出页面(因为使用 innerHTML的实例生成需要更新DOM)
    setTimeout((tar) => {
      tar.style.opacity = 1
      tar.style.transform = 'translate(0)'
    }, 200, this.el)

    this.el.addEventListener('click', (e) => {
      let tar = e.target.id ? e.target.id : e.target.className
      switch (tar) {
        case this.prefix + 'btngroup':
          this.show()
          break;
        default:
          // statements_def
          break;
      }
    }, true)
  }

  /*显示元素,或者显示子页面元素*/
  show(pageName = '', data) {
    if (!this.el) return console.log('未初始化')

    if (this.el.style.transform == 'translate(150%)') {
      this.el.style.opacity = 1
      this.el.style.transform = 'translate(0)'
    } else {
      this.el.style.opacity = 0
      this.el.style.transform = 'translate(150%)'
    }
  }

  send(action, data = null) {
    let e
    if (data) {
      e = new Event(action)
    } else {
      e = new CustomEvent(action, {
        detail: {
          data,
        },
        bubbles: false, //是否冒泡
        cancelable: false //是否取消默认事件
      })
    }
    this.el.dispatchEvent(e)
  }
}
export default createSubPage